﻿using OccurrencesCore.Model;
using OccurrencesCore.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OccurrencesWeb.UserControls.Occurrences
{
    public partial class OccurenceInvoices : System.Web.UI.UserControl
    {
        private List<Invoice> invoices
        {
            get
            {
                List<Invoice> cacheInvoices = Session[GetAttachmentSessionKey()] as List<Invoice>;
                return cacheInvoices != null ? cacheInvoices : new List<Invoice>();
            }
            set
            {
                Session[GetAttachmentSessionKey()] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;
            ClearSessionInvoices();
            RefreshInvoicesRepeater();
        }

        private string GetAttachmentSessionKey()
        {
            return "INVOICE_CACHE_KEY";
        }

        protected void InsertInvoiceToSession(Invoice invoice)
        {
            List<Invoice> newInvoicesList = invoices;
            newInvoicesList.Add(invoice);
            invoices = newInvoicesList;
        }

        protected void ClearSessionInvoices()
        {
            invoices = new List<Invoice>();
        }

        protected void RefreshInvoicesRepeater()
        {
            rptInvoices.DataSource = invoices;
            rptInvoices.DataBind();
        }

        protected void rptInvoices_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Invoice invoice = e.Item.DataItem as Invoice;
                Literal litInvoiceNumber = e.Item.FindControl("litInvoiceNumber") as Literal;
                litInvoiceNumber.Text = invoice.Number;
            }
        }

        protected void btnAddInvoice_Click(object sender, EventArgs e)
        {
            Invoice invoice = new InvoiceService().GetInvoiceInformationFromSAP(txtNewInvoiceNumber.Text);
            InsertInvoiceToSession(invoice);
            RefreshInvoicesRepeater();
        }


    }
}